import java.util.HashMap;
import java.util.Map;

public class Solution947 {
    public int removeStones(int[][] stones) {
        UnionUtil unionFind = new UnionUtil();

        for (int[] stone : stones) {
            unionFind.union(~stone[0], stone[1]);
        }
        return stones.length - unionFind.getCount();
    }

    private class UnionUtil{
        HashMap<Integer,Integer> Util;
        int Count;
        UnionUtil(){
            Util=new HashMap<>();
            Count=0;
        }
        int getCount(){
            return Count;
        }
        int find(int element){
            if(Util.containsKey(element)==false){
                Util.put(element,element);
                Count++;
            }
            if(Util.get(element)!=element){
                Util.put(element,find(Util.get(element)));
            }
            return Util.get(element);
        }
        void union(int x,int y){
            int rootx=find(x);
            int rooty=find(y);
            if(rootx==rooty){
                return;
            }
            Util.put(rootx,rooty);
            Count--;

        }
    }
}
